package com.jt.resource.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @author tang
 * @data 2021/9/24
 * @apiNode
 */
//在过滤器的层面实现跨域配置
//@Configuration
public class CorsFilterConfig {
    /**
     * 定义跨域过滤器的配置,并且将其注册到spring容器中
     * @return
     */
    @Bean
    public FilterRegistrationBean<CorsFilter> filterFilterRegistrationBean(){
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        configSource.registerCorsConfiguration("/**", corsConfiguration);
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.setAllowCredentials(true);
        FilterRegistrationBean<CorsFilter> fBean = new FilterRegistrationBean<>(new CorsFilter(configSource));
        fBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return fBean;
    }
}
